﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xproject.Framework.Core;
using Xproject.Framework.Core.DataContext;
using Xproject.Framework.Core.Repositories;
using Model.WeiXin;
using Repository.WeiXinProject;
using Xproject.Util;
using Repository.Util;
using Model.Util;
using Services.ZXBuiness;
using Model.WXshopBuiness;
using Model.Const;
using Core.WeiXin;

namespace Services.WeiXinProject
{
    public class WeiXinMessageServices:Service
    {
        IRepositoryAsync<WeiXinMessage> m_WeiXinMessageRepository;                          
        public WeiXinMessageServices(IDataContextAsync dataContext) : base(dataContext)
        {
            m_WeiXinMessageRepository = m_UnitOfWork.RepositoryAsync<WeiXinMessage>();
        }
        /// <summary>
        /// 发送订单支付成功通知                  
        ///{{first.DATA}}
        ////商品名称：{{keyword1.DATA}}
        ///订单编号：{{keyword2.DATA}}
        ///支付金额：{{keyword3.DATA}}
        ///{{remark.DATA}}'
        /// 订单支付成功通知：
        /// 尊敬的<会员名> 您的订单：<产品名>，已支付成功
        /// 您的订单号是：<订单号> （可以点击url）
        /// 请您继续关注订单信息，我们将立即安排发货！
        /// </summary>
        /// <returns></returns>
        public int SendOrderPaySuccessMessage( string sender,
            string senderUserId,string UserId,string touserOpenid, string url,string appid,string nickname,string productname,string orderno,string money)
        {
            ///先插入一个记录到数据库，
            WeiXinMessage message = new WeiXinMessage();
            message.AppID = appid;
            message.SendTime = message.CreateTime = message.ConfirmTime = DateTime.Now;
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add(productname, "");
            dict.Add(orderno, "");
            dict.Add(money,"");
            string remarks  = "我们会第一时间通知您订单的最新状态。祝您生活愉快！--"+CommonHelper.GetAppSettings("MessageSender");
            string subject = "尊敬的" + nickname + "您好，您的订单已成功支付！";
            message.MessageBody = GetMessageBodyJson(EnumMessageType.订单支付成功通知, touserOpenid, subject, remarks, dict, "");
            message.Content = remarks;
            message.MessageID = Guid.NewGuid().ToString();
            message.MsgType = "1";
            message.OpenId = touserOpenid;
            message.Sender = CommonHelper.GetAppSettings("MessageSender");
            message.UserID = UserId;
            message.EntityState = EntityState.Added;
            message.TemplateID = GetTemplateId(EnumMessageType.订单支付成功通知);
            message.Subject = subject;
            m_WeiXinMessageRepository.Insert(message);
            m_UnitOfWork.SaveChanges();

            WeiXinHelper.SendMessage(message.MessageID, message.MessageBody);
            ///然后再调用微信发送模板通知消息
            return 0;
        }

        /// <summary>
        /// 发送订单已发货通知信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="senderUserId"></param>
        /// <param name="UserId"></param>
        /// <param name="touserOpenid"></param>
        /// <param name="url"></param>
        /// <param name="appid"></param>
        /// <param name="nickname"></param>
        /// <param name="productname"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public int SendOrderShippingMessage(string sender,
              string senderUserId, string UserId, string touserOpenid, string url, string appid, string nickname, 
              string productname, string orderno,string KDNumber,string kdname)
        {
            ///先插入一个记录到数据库，
            WeiXinMessage message = new WeiXinMessage();
            message.AppID = appid;
            message.SendTime = message.CreateTime = message.ConfirmTime = DateTime.Now;
            Dictionary<string, string> dict = new Dictionary<string, string>();
          
            dict.Add(orderno, "");
            dict.Add(kdname, "");
            dict.Add(KDNumber, "");
            string subject = "尊敬的" + nickname + "您好，您的订单已发货！";
            string remarks ="请及时查询订单物流信息。祝您生活愉快！--"+ sender;
            message.MessageBody = GetMessageBodyJson(EnumMessageType.订单已发货, touserOpenid, subject, remarks, dict, "");
            message.Content = remarks;
            message.MessageID = Guid.NewGuid().ToString();
            message.MsgType = "1";
            message.OpenId = touserOpenid;
            message.Sender = CommonHelper.GetAppSettings("MessageSender");
            message.UserID = UserId;
            message.EntityState = EntityState.Added;
            message.TemplateID = GetTemplateId(EnumMessageType.订单已发货);
            message.Subject = subject;
            m_WeiXinMessageRepository.Insert(message);
            m_UnitOfWork.SaveChanges();

            WeiXinHelper.SendMessage(message.MessageID, message.MessageBody);
            ///然后再调用微信发送模板通知消息
            return 0;
        }


        public int SendOrderUserRegisterMessage(string sender, string senderUserId, string UserId, string touserOpenId, string url, string appid, string nickname
            )
        {
            ///先插入一个记录到数据库，
            WeiXinMessage message = new WeiXinMessage();
            message.AppID = appid;
            message.SendTime = message.CreateTime = message.ConfirmTime = DateTime.Now;            
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add(sender, "");
            dict.Add(DateTime.Now.ToString(), "");

           
            string subject = "感谢关注"+sender;
            string remarks = "尊敬的" + nickname + "您好，欢迎关注，这儿还有更精彩的，点我，快看看吧^_^!";
            message.MessageBody = GetMessageBodyJson(EnumMessageType.事项提醒接收确认, touserOpenId, subject, remarks, dict, url);         
            message.Content = remarks;
            message.MessageID = Guid.NewGuid().ToString();
            message.MsgType = "1";
            message.OpenId = touserOpenId;
            message.Sender = CommonHelper.GetAppSettings("MessageSender");
            message.UserID = UserId;
            message.EntityState = EntityState.Added;
            message.TemplateID = GetTemplateId(EnumMessageType.事项提醒接收确认);
            message.Subject = subject;
            m_WeiXinMessageRepository.Insert(message);
            m_UnitOfWork.SaveChanges();

            WeiXinHelper.SendMessage(message.MessageID, message.MessageBody);
            ///然后再调用微信发送模板通知消息
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="openId">touser openid</param>         
        /// <param name="subject">模板标题</param>
        /// <param name="remark"></param>
        /// <param name="dict"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetMessageBodyJson(EnumMessageType type, string openId,   string subject, string remark, Dictionary<string, string> dict, string url = "")
        {
             
            StringBuilder sb = new StringBuilder();
            sb.Append(" { ");
            sb.Append(" \"touser\" : \"" + openId + "\" ,");
            sb.Append(" \"template_id\" : \"" + GetTemplateId(type) + "\" ,");
            sb.Append(" \"url\" : \"" + url + "\" ,");

            sb.Append(" \"data\" : { ");
            sb.Append(" \"first\"  : { \"value\" : \"" + subject + "\" , \"color\" : \"#173177\" } ,");
            int i = 1;
            foreach (string key in dict.Keys)
            {
                string color = dict[key];
                if (string.IsNullOrEmpty(color))
                {
                    color = "#173177";
                }
                sb.Append(" \"keyword" + i + "\"  : { \"value\" : \"" + key + "\" , \"color\" : \"" + color + "\" } , ");
                i++;
            }
            sb.Append(" \"remark\"  : { \"value\" : \"" + remark + "\" , \"color\" : \"#173177\" } } ");
            sb.Append(" } ");
            return sb.ToString().Replace("\\", "");
        }
      

        /// <summary>
        /// 预定义写死了一些templateID
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string GetWJSTemplateId(EnumMessageType type)
        {
            switch (type)
            {
                case EnumMessageType.推荐会员消费通知:
                    return "SFjDHJz1gQPqsGGbkDcetlqo0APbZuWerX2s4xTC4go";
                case EnumMessageType.事项提醒接收确认:
                    return "kztHD98SgkmMEIKjQndl6eCw8xGjguMBxktVpj6eFNY";
                case EnumMessageType.推荐订单完成支付通知:
                    return "ATby9J_7J0yXHLuVs88vdk-PNm0ZlXYToher5l5AbQs";
                case EnumMessageType.订单支付成功通知:
                    return "mxBMj8BTjFj-oVO7OW-ghVSpplamTv0ZswfY8rmi-CY";
                case EnumMessageType.消费通知:
                    return "zYzFe8rsBpiSz34UTPp8WILZ6PtPRrUyiGwUJuGI9wo";
                case EnumMessageType.订单生成通知:
                    return "OxknMf8fLBp8T6yLgj08OmGI51VVQnK1hUm3HY-44rM";
                case EnumMessageType.申请经销商提醒:
                    return "mB9wfned-sD_FrWOb-o7coJAAFDN-Z5TSkpYdzVIUt4";//申请提现 
            }
            return "";
        }

        public static string GetWebConfig(string key)
        {
            string templateId =CommonHelper.GetAppSettings(key);
            return templateId;
        }
        public static string GetTemplateId(EnumMessageType type)
        {
            string template =  GetWebConfig(type.ToString());
            if (string.IsNullOrEmpty(template))
            {
                throw new Exception("没有找到模板消息！");
            }
            return template;
        }
    }
}
